package com.hyjoy.dao.impl;

import com.hyjoy.dao.UserDao;
import com.hyjoy.entity.User;
import com.hyjoy.util.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

/**
 * Created by hyjoy on 2018/4/4.
 */
public class UserDaoImpl implements UserDao {

    /**
     * 用户注册
     *
     * @param user
     * @throws Exception
     */
    public void save(User user) throws Exception {
        QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "insert into user values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        queryRunner.update(sql, user.getUid(), user.getUsername(), user.getPassword(),
                user.getName(), user.getEmail(), user.getTelephone(), user.getBirthday(),
                user.getSex(), user.getState(), user.getCode());
    }

    public User getByCode(String code) throws Exception {
        QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select * from user where code = ? limit 1";
        return queryRunner.query(sql, new BeanHandler<>(User.class), code);
    }

    public void update(User user) throws Exception {
        QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "update user set password = ?,sex = ?,state = ?,code = ? where uid = ?";
        qr.update(sql, user.getPassword(), user.getSex(), user.getState(), user.getCode(), user.getUid());
    }

    public User getByUsernameAndPwd(String username, String password) throws Exception {
        QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select * from user where username = ? and password = ? limit 1";
        return qr.query(sql, new BeanHandler<>(User.class), username, password);
    }
}
